<template>
  <div class="login-form">
    <div class="toggle">
      <a @click="isMsgLoginChange" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLoginChange" href="javascript:;" v-if="!isMsgLogin">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <Form ref="formCom" :validation-schema="formSchema" autocomplete="off">
        <template v-if="!isMsgLogin">
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-user"></i>
              <Field name="account" v-model="form.account" type="text" placeholder="请输入账号" />

            </div>
            <ErrorMessage name="account" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
            <!-- <div class="error"><i class="iconfont icon-warning" />请输入手机号</div> -->
          </div>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-lock"></i>
              <Field name="password" v-model="form.password" type="password" placeholder="请输入密码" />

            </div>
            <ErrorMessage name="password" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
        </template>

        <template v-else>
          <div class="form-item" v-if="isMsgLogin">
            <div class="input">
              <i class="iconfont icon-user"></i>
              <Field name="mobile" v-model="form.mobile" type="text" placeholder="请输入手机号" />

            </div>
            <ErrorMessage name="mobile" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
          <div class="form-item" v-if="isMsgLogin">
            <div class="input">
              <i class="iconfont icon-code"></i>
              <Field name="code" v-model="form.code" type="password" placeholder="请输入验证码" />

              <span class="code" @click="send">
                {{time>0?time+'秒':'发送验证码'}}
              </span>
            </div>
            <ErrorMessage name="code" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
        </template>

        <div class="form-item">
          <div class="agree">
            <Field name="isAgree" as='XtxCheckbox' v-model="form.isAgree" />

            <span>我已同意</span>
            <a href="javascript:;">《隐私条款》</a>
            <span>和</span>
            <a href="javascript:;">《服务条款》</a>
          </div>

          <ErrorMessage name="isAgree" v-slot="{ message }">
            <div class="error" v-if="message">
              <i class="iconfont icon-warning" />{{ message }}
            </div>
          </ErrorMessage>
        </div>
        <a href="javascript:;" class="btn" @click="submit">登录</a>
      </Form>
    </div>
    <div class="action">
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import { Form, Field, ErrorMessage } from 'vee-validate'
// 表单校验规则
import schema from '@/utils/schema'
import { userAccountLogin, userMobileLoginMsg, userMobileLogin } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Message from 'erabbit-ui/packages/components/Message'
// 从vueuse中获取倒计时函数
import { useIntervalFn } from '@vueuse/core'
export default {
  name: 'LoginForm',
  components: { Form, Field, ErrorMessage },
  setup() {
    const isMsgLogin = ref(false)
    const isMsgLoginChange = () => {
      isMsgLogin.value = !isMsgLogin.value
    }
    // 表单信息对象
    const form = ref({
      isAgree: true,
      mobile: null,
      account: null,
      password: null,
      code: null
    })
    const formCom = ref(null)
    // 切换表单时重置
    watch(isMsgLogin, () => {
      form.value = {
        isAgree: true,
        mobile: null,
        account: null,
        password: null,
        code: null
      }
      formCom.value.resetForm()
    })
    // 兜底校验
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = await formCom.value.validate()
      if (valid) {
        //   校验成功
        // console.log(valid)
        // userAccountLogin

        try {
          // console.log(form.value)
          // 有可能是短信登录也有可能是账号登录,由isMsgLogin判断
          let data = null
          if (!isMsgLogin.value) {
            const pushData = { account: form.value.account, password: form.value.password }
            data = await userAccountLogin(pushData)
          } else {
            data = await userMobileLogin({ mobile: form.value.mobile, code: form.value.code })
            // console.log(data)
          }
          // console.log(data)
          const { id, account, mobile, avatar, nickname, token } = data.result
          store.commit('user/setProfile', {
            id,
            account,
            mobile,
            avatar,
            nickname,
            token
          })
          //   跳转页面
          router.push('/')
        } catch (e) {
          // 错误提示
          // console.log(e.response.data.message);
          // Message({type:'warn|success|error',text:'文字'})
          Message({
            type: 'error',
            text: e.response.data.message || '登录失败'
          })
        }
      }
    }
    // 表单验证流程
    // 数据
    // 校验规则
    // 表单项指定校验规则
    // 表单项绑定数据
    // 使用错误组件显示错误
    // formSchema

    const { account, password, mobile, code, isAgree } = schema
    const formSchema = { account, password, mobile, code, isAgree }

    // 发送验证码
    // 验证码倒计时变量
    const time = ref(0)
    const { pause, resume, isActive } = useIntervalFn(
      () => {
        time.value--
        // console.log(time.value)
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      false
    )
    const send = async () => {
      // 表单校验
      const valid = mobile(form.value.mobile)
      if (valid === true) {
        //验证通过
        if (!isActive.value) {
          await userMobileLoginMsg(form.value.mobile)
          Message({ type: 'success', text: '发送成功' })
          time.value = 60
          resume()
        }
      } else {
        //验证失败
        // 弹出校验提示
        formCom.value.setFieldError('mobile', valid)
      }
    }

    return {
      isMsgLogin,
      isMsgLoginChange,
      form,
      formSchema,
      submit,
      formCom,
      send,
      time
    }
  }
}
</script>
<style lang="less" scoped>
// 账号容器
.login-form {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: var(--xtx-color);
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: var(--price-color);
          }
          &.active,
          &:focus {
            border-color: var(--xtx-color);
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: var(--price-color);
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: var(--xtx-color);
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>